import 'dart:convert';

import 'package:get/get_state_manager/src/rx_flutter/rx_disposable.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:vischat/core/service/storage/secure_auth.dart';
import 'package:vischat/core/service/storage/secure_conversation.dart';
import 'package:vischat/core/service/storage/storage_manager.dart';
import 'package:vischat/data/models/user_model.dart';

class SecureLocal extends GetxService {
  final StorageManager _storage;

  late SecureAuthStorage _tokenStorage;
  late SecureConversationStorage _conversationStorage;

  SecureLocal(this._storage) {
    _tokenStorage = _storage.tokenStorage;
    _conversationStorage = _storage.conversationStorage;
  }

  /// 获取token
  String? getToken() => _tokenStorage.getToken();

  /// 存储token
  Future<void> saveToken(String token) async =>
      await _tokenStorage.saveToken(token);

  /// 删除token
  Future<void> deleteToken() async => await _tokenStorage.deleteToken();

  /// 获取用户
  UserModel? getUser() {
    Map<String, dynamic>? data = _tokenStorage.getUser();
    return data == null ? null : UserModel.fromJson(data);
  }

  /// 保存用户
  Future<void> saveUser(UserModel user) async =>
      await _tokenStorage.saveUser(user.toJson());

  /// 删除用户
  Future<void> deleteUser() async => await _tokenStorage.deleteUser();

  /// 保存会话列表
  Future<void> saveConversations(List<V2TimConversation?> conversations) async {
    final conversationsJson = json.encode(
      conversations.map((c) => c?.toJson()).toList(),
    );
    await _conversationStorage.saveConversations(conversationsJson);
  }

  /// 获取会话列表
  List<V2TimConversation?> getConversations() {
    String conversationsJson = _conversationStorage.getConversations();
    if (conversationsJson.isNotEmpty) {
      final List<dynamic> conversationsList = json.decode(conversationsJson);
      final List<V2TimConversation?> conversations =
          conversationsList.map<V2TimConversation>((jsonData) {
            return V2TimConversation.fromJson(jsonData);
          }).toList();
      return conversations;
    } else {
      return [];
    }
  }
}
